package sessionbean;

import entity.Item;
import entity.Price;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.ejb.EJB;
import javax.ejb.Stateless;

@Stateless
public class HarvesterSession {
    private static final Logger logger = Logger.getLogger(HarvesterSession.class.getName());
    @EJB
    private HTMLDownloaderSession htmlDownloaderSession;
    
    public List<Item> harvestPrices(String url) {
        List<Item> items = new ArrayList<Item>();
        String html = htmlDownloaderSession.processURL(url);
        List<URL> urls = findItems(html);
        
        for (URL itemURL : urls) {
            String bookHtml = htmlDownloaderSession.processURL(itemURL);
            Item item = parseItem(bookHtml);
            
            if (item != null) {
                items.add(item);
            }
        }
        
        return items;
    }    
    
    public Item parseItem(String html) {
        logger.log(Level.INFO, "Finding item data in html page.");
        Item item = new Item();
        Price price = new Price();
        
        try {
            html = html.split("<span id=\"btAsinTitle\">")[1];
            String title = html.split("<span style")[0];
            item.setTitle(title.substring(0, title.indexOf(" <span")));
            html = html.split("priceLarge\">\\n        ")[1];

            item.getPrices().add(price);

            price.setDateSeen(new Date());
            price.setItem(item);
            price.setPrice(new BigDecimal(html.split(" ")[0].substring(1).trim()));
        } catch (Exception exception) {
            return null;
        }
           
        return item;
    }  
    
    public List<URL> findItems(String html) {
        logger.log(Level.INFO, "Finding items in wishlist html.");
        List<URL> urls = new ArrayList<URL>();
        String[] split = Pattern.compile("small productTitle\"><strong>(\\n)*<a href=\"").split(html);
        
        if (split.length < 1) {
            return urls;
        }
        
        for (int i=1; i<split.length; i++) {
            try {
                urls.add(new URL(split[i].substring(0, split[i].indexOf("\""))));
            } catch (MalformedURLException ex) {
                logger.log(Level.SEVERE, null, ex);
            }
        }
        
        return urls;
    }    
}
